package org.example.springextension.listener;

import com.rabbitmq.client.Channel;
import org.example.springextension.constants.Constants;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

import org.springframework.stereotype.Component;

//@Component
public class AckListener {
    //@RabbitListener(queues = Constants.ACK_QUEUE)
    public void handMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try{
            //消费者逻辑
            System.out.printf("接收到消息: %s, deliveryTag: %d \n", new String(message.getBody(),"UTF-8"), message.getMessageProperties().getDeliveryTag());

            //处理业务逻辑
            System.out.println("业务逻辑处理");
            int sum=20/0;
            System.out.println("业务处理完成");
            //肯定确认
            channel.basicAck(deliveryTag,false);
            //遇到这种情况的时候，消息会不断的进行重发，遇见异常的时候就会这样
            //在我的演示的请情况下，unnack上面依然为0，但是在老师上面的时候，unnack为1

        }catch (Exception e){
            //否定确认
            channel.basicNack(deliveryTag,false,true);
        }
    }
    //none的演示情况下
    //这种情况下，不管消息是否被正常处理的时候，消息都会丢失
    //@RabbitListener(queues = Constants.ACK_QUEUE)
    public void handMessage1(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try{
            //消费者逻辑
            System.out.printf("接收到消息: %s, deliveryTag: %d \n", new String(message.getBody(),"UTF-8"), message.getMessageProperties().getDeliveryTag());

            //处理业务逻辑
            System.out.println("业务逻辑处理");
            int sum=20/0;
            System.out.println("业务处理完成");
            //肯定确认
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            //否定确认
            channel.basicNack(deliveryTag,false,true);
        }
    }
    //manual
    //手动确认的机制下，消息必须在成功处理消息后显式调用basicAck方法
    //如果消息未被确认的话，会重新进行发送消息，即使消息处理失败的情况下，提高了可靠性
    //消息一般有两个途径，意一是处理成功，显示确认，另一种则是未被处理成功，显示unnack
    @RabbitListener(queues = Constants.ACK_QUEUE)
    public void handMessage2(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try{
            //消费者逻辑
            System.out.printf("接收到消息: %s, deliveryTag: %d \n", new String(message.getBody(),"UTF-8"), message.getMessageProperties().getDeliveryTag());

            //处理业务逻辑
            System.out.println("业务逻辑处理");
            int sum=20/0;
            System.out.println("业务处理完成");
            //肯定确认
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            //否定确认
            channel.basicNack(deliveryTag,false,true);
        }
    }
}
